package com.CampusForum.community.controller.interceptor;

import com.CampusForum.community.dao.LoginTicketMapper;
import com.CampusForum.community.dao.UserMapper;
import com.CampusForum.community.entity.LoginTicket;
import com.CampusForum.community.entity.User;
import com.CampusForum.community.util.CookieUtil;
import com.CampusForum.community.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@Component
public class LoginTicketInterceptor implements HandlerInterceptor {
    @Autowired
    private LoginTicketMapper loginTicketMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private HostHolder hostHolder;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取cookie, 检测是否存在用户凭证ticket
        String ticket = CookieUtil.getValue(request, "ticket");
        if (ticket == null) {
            // 用户凭证不存在
            return true;
        }
        LoginTicket loginTicket = loginTicketMapper.getByTicket(ticket);
        if (loginTicket == null) {
            // 凭证不存在
            return true;
        }
        int userId = loginTicket.getUserId();
        User user = userMapper.getById(userId);
        if (user != null && loginTicket.getStatus() == 0 && loginTicket.getExpired().after(new Date())) {
            // 用户存在 凭证有效且未过期
            hostHolder.setUser(user);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        User user = hostHolder.getUser();
        if(user != null && modelAndView != null) {
            // 用户存在且视图要展示
            modelAndView.addObject("loginUser", user);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清除用户
        hostHolder.clear();
    }
}
